package com.jsn.android.audio2

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.observe
import com.jsn.android.audio2.databinding.ActivityPlayBinding
import com.jsn.baselibx.ui.BaseActivity
import com.jsn.baselibx.utils.Logs
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_play.*
import kotlinx.coroutines.*
import java.io.InputStream
import java.lang.Exception
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.system.measureTimeMillis

@Suppress("BlockingMethodInNonBlockingContext")
class PlayActivity : BaseActivity<ActivityPlayBinding>() {

    var job = SupervisorJob()

    val scope = CoroutineScope(Dispatchers.IO + job)

    //player initilaized  or not
    private var started = MutableLiveData<Boolean>().apply { value = false }

    //is playing or not
    private var playing = MutableLiveData<Boolean>().apply { value = false }

    var inputStream: InputStream? = null

    val fileName = "1583905552833.pcm"

    val audioPlayer = AudioPlayer()

    val string="RIFF"

    override fun getContentView(): Int {

        return R.layout.activity_play
    }



    override fun initUI() {

        for (i in 0 until string.length) {
            Logs.e("riff: ${string[i].toInt()}")
        }

        //play
        bt.setOnClickListener {
            prepare()
            if (started.value!!) {
                play()
                toast("playing $fileName")
                playing.value = true
            } else {
                toast("fail play")
                return@setOnClickListener
            }
        }

        //pause
        bt_stop.setOnClickListener {
            stop()
        }

        playing.observe(this) { isPlaying ->
            bt.isEnabled = !isPlaying
            bt_stop.isEnabled = isPlaying
        }

    }

    private fun play() {
        scope.launch {
            val data = ByteArray(audioPlayer.bufferSize)
            var read = 0
            while (loop.get()) {
                try {
                    read = inputStream!!.read(data, 0, audioPlayer.bufferSize)
                    if (read == -1) break
                    audioPlayer.play(data, 0, read)
                } catch (e: Exception) {
                    inputStream?.close()
                    break
                }
            }
            //play complete ,we set to start state
            audioPlayer.pause()
            inputStream?.close()
            playing.postValue(false)
        }



    }

    fun prepare() {
        started.value = audioPlayer.startPlayer()
        val open: InputStream = assets.open(fileName).also { inputStream = it }
    }

    //set ture unless we press the stop button
    var loop = AtomicBoolean(true)

    fun stop() {
        //job.cancelAndJoin()
        loop.set(false)      //operation done atomically
        Thread.sleep(100)  //
        audioPlayer?.pause()
        inputStream?.close()
        loop.set(true)
        playing.value = false
    }

    override fun initData() {
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
        audioPlayer.stop()
        inputStream?.close()
        started.value = false
    }
}